<?php
class WxauthController extends Controller
{
	public function actionWxLogin()
	{
		app()->user->logout();
		$callback_landing = app()->request->getParam('callback_landing', '');
		
		$id_wxplatform = app()->request->getParam('id_wxplatform', Wxplatform::DEFAULT_ID);
		$wxplatform = Wxplatform::model()->findByPk($id_wxplatform);
		
		app()->WxInterface->switchPlatform($wxplatform);
		return app()->WxInterface->oAuthLogin(
			aUrl('/wxauth/authcallback'),
			array(
				'callback_landing' => $callback_landing, 
				'id_wxplatform' => $id_wxplatform
			),
			'code', 'snsapi_userinfo'
		);
	}
	
	public function actionWxLogout()
	{
		app()->user->logout();
		//$this->redirect('/wxuser/mymcards');
	}
	
	public function actionAuthcallback()
	{
		$code = app()->request->getParam('code', '');
		$state = app()->request->getParam('state', array());
		
		if($state){
			$stateValue = app()->WxInterface->getOauth2State($state);
		}
		
		$wxplatform = Wxplatform::model()->findByPk($stateValue->id_wxplatform);
		
		if(!empty($wxplatform)){
			app()->WxInterface->switchPlatform($wxplatform);
			
			$retAccessToken = app()->WxInterface->getOauth2AccessToken($code);
			
			if(!isset($retAccessToken->errcode)){
				$retUserInfo = app()->WxInterface->getUserInfo($retAccessToken->access_token, $retAccessToken->openid);
				
				//$retUserInfo = app()->WxInterface->getCgibinUserInfo($retAccessToken->openid);
				if(!isset($retUserInfo->errcode)){
					$dbWxuser = Wxuser::model()->findByAttributes(array(
						'openid' => $retUserInfo->openid, 
						'id_wxplatform' => $stateValue->id_wxplatform
					));
					if(empty($dbWxuser)){
						$dbWxuser = new Wxuser();
						$dbWxuser->id_wxplatform = $stateValue->id_wxplatform;
						$dbWxuser->createtime = date('Y-m-d H:i:s');
					}
					
                    $dbWxuser->nickname = $retUserInfo->nickname;
                    $dbWxuser->nickname_encode = base64_encode($retUserInfo->nickname);
					$dbWxuser->gender = $retUserInfo->sex;
					$dbWxuser->unionid =  isset($retUserInfo->unionid)?$retUserInfo->unionid:'';
					$dbWxuser->openid = $retUserInfo->openid;
					$dbWxuser->avatar_url = $retUserInfo->headimgurl;
					$dbWxuser->province = $retUserInfo->province;
					$dbWxuser->city = $retUserInfo->city;
					$dbWxuser->country = $retUserInfo->country;
					//新增字段
					$dbWxuser->language = $retUserInfo->language;
					$dbWxuser->privilege = json_encode($retUserInfo->privilege);
					if($dbWxuser->save()){
						app()->user->wxLogin($dbWxuser);
			
						$this->redirect($stateValue->callback_landing);
					}
				}
			}
		}
	}
	
	public function accessRules()
	{
		return array(
			array(
				'allow',
				'actions' => array('wxlogin', 'wxlogout', 'authcallback'),
				'expression' => 'app()->user->anyone'
			),
			
			array(
				'deny',	//should be 'deny', 'allow' is used to give convenient to make test
				'users' => array('*'),
				'redirect' => '/user/login'
			)
		);
	}
}